package com.dushibao.manage;

import com.alibaba.fastjson.JSON;
import com.dushibao.entity.Resource;
import com.dushibao.service.ResourceService;
import com.dushibao.service.impl.ResourceServiceImpl;
import com.dushibao.utils.AppUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/ServletUpload")
public class ServletUpload extends HttpServlet {
    ResourceService resourceService = new ResourceServiceImpl();

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            uploadFiles(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void uploadFiles(HttpServletRequest request, HttpServletResponse response) throws Exception {

        request.setCharacterEncoding("UTF-8");

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 解析请求的内容提取文件数据
        List<FileItem> formItems = upload.parseRequest(request);
        FileItem item = formItems.get(0);

        // 迭代表单数据
        // 处理不在表单中的字段，即文件
        if (!item.isFormField()) {
            String fileName = item.getName(); //获取上传的文件名
            String fileType=fileName.substring(fileName.lastIndexOf(".")+1);
            //定义上传文件的存放路径
            String uploadFolder = "/upload/";
            String path = AppUtils.getValue("upload")+ uploadFolder;
            //定义上传文件的完整路径
            String fileSaveName= new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
            fileSaveName+="."+fileType;
            String filePath = String.format("%s/%s",path,fileSaveName);
            File storeFile = new File(filePath);
            //如果父目录不存在则去创建
            if(!storeFile.getParentFile().exists()){
                storeFile.getParentFile().mkdirs();
            }
            // 在控制台输出文件的上传路径
            System.out.println(filePath);
            // 保存文件到硬盘
            item.write(storeFile);
            String fileSavePath = uploadFolder+fileSaveName;

            Resource resource = new Resource();
            resource.setPath(fileSavePath);
            resourceService.save(resource);

            response.getWriter().write(JSON.toJSONString(resource));
        }
    }
}
